/**
 * @ClassName: 循环队列
 * @author:
 * @Description:
 * @Date
 **/
public class LoopQueue<E> implements Queue<E> {
    private E[] data;
    private int front, tail;
    private int size;

    public LoopQueue(int capacity) {
        data = (E[]) new Object[capacity + 1];
        front = tail = 0;
        size = 0;
    }

    public LoopQueue() {
        this(10);
    }


    public int getCapacity() {
        return data.length - 1;
    }

    @Override
    public void enqueue(E e) {
//        if ((tail + 1) % data.length == front) {
//            resize(getCapacity() * 2);
//        }
        //改成不浪费一个空间的形式
        if (size == getCapacity()) {
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        //防止tail加1后数组越界
        tail = (tail + 1) % data.length;
        size++;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity + 1];
        for (int i = 0; i < size; i++) {
            //防止i加上原来的front后数组越界
            newData[i] = data[(i + front) % data.length];
        }
        data = newData;
        front = 0;
        tail = size;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("queue is empty");
        }
        E ret = data[front];
        data[front] = null;
        //弹出队首的元素，front本身要加1，但要防止数组越界问题
        front = (front + 1) % data.length;
        size--;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("queue is empty");
        }
        return data[front];
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Queue: ");
        builder.append("front [");
//        for (int i = front; i != tail; i = (i + 1) % data.length) {
//            builder.append(data[i]);
//            if ((i + 1) % data.length != tail) {
//                builder.append(",");
//            }
//        }
        //改成不浪费元素的形式
        for (int i = 0; i < size; i++) {
            builder.append(data[(front + i) % data.length]);
            if ((front + i + 1) % data.length != tail) {
                builder.append(",");
            }
        }
        builder.append("] tail");
        return builder.toString();
    }
}
